<template>
  <div class="survey-wrap">
    <!-- 顶部：新增 + 搜索 -->
    <div class="tool-bar">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAdd">
        新增问卷
      </el-button>
      <el-form :inline="true" size="small" style="margin-left: auto;">
        <el-form-item style="margin-bottom: 0;">
          <el-input
            v-model="keyword"
            placeholder="请输入小区/问卷名称"
            clearable
            style="width: 260px"
            @clear="fetchList"
            @keyup.enter.native="fetchList"
          />
        </el-form-item>
        <el-form-item style="margin-bottom: 0;">
          <el-button type="primary" @click="fetchList">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      size="small"
      style="width: 100%"
      header-cell-class-name="table-head"
    >
      <el-table-column label="小区" width="120">
        <template #default="{ row }">{{ row.communityName }}</template>
      </el-table-column>
      <el-table-column label="问卷名称" width="150">
        <template #default="{ row }">{{ row.questionnaireName }}</template>
      </el-table-column>
      <el-table-column label="问卷描述" min-width="180">
        <template #default="{ row }">{{ row.questionnaireDesc }}</template>
      </el-table-column>
      <el-table-column label="问题数量" width="100">
        <template #default="{ row }">{{ row.questionNum }}</template>
      </el-table-column>
      <el-table-column label="发布时间" width="150">
        <template #default="{ row }">{{ row.questionnaireStartTime }}</template>
      </el-table-column>
      <el-table-column label="结束时间" width="150">
        <template #default="{ row }">{{ row.questionnaireEndTime }}</template>
      </el-table-column>
      <el-table-column label="答卷数量" width="100">
        <template #default="{ row }">{{ row.questionnaireNum }}</template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag
            :type="row.statusName === '已结束' ? 'success' : (row.statusName === '进行中' ? 'warning' : 'info')"
            size="mini"
          >
            {{ row.statusName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="text" size="mini" @click="handleDetail(row)">详情</el-button>
          <el-button type="text" size="mini" @click="openEditDialog(row)">编辑</el-button>
          <el-button type="text" size="mini" style="color:#f56c6c6c" @click="handleDel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑问卷 Dialog -->
    <el-dialog :visible.sync="editDialogVisible" title="编辑问卷">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="问卷名称">
          <el-input v-model="editForm.questionnaireName"></el-input>
        </el-form-item>
        <el-form-item label="问卷描述">
          <el-input v-model="editForm.questionnaireDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'SurveyMgmt',
  data() {
    return {
      keyword: '',
      pageSize: 10,
      currentPage: 1,
      
      total: 0,
      list: [],

      // 编辑 Dialog
      editDialogVisible: false,
      editForm: {}
    }
  },
  computed: {
    tableData() {
      return this.list
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    // 获取列表（分页 + 搜索）
     fetchList() {
  const payload = {
    page: this.currentPage,
    size: this.pageSize,
    communityName: this.keyword,
    questionnaireName: this.keyword
  };

  const url = this.keyword
    ? "http://localhost:8080/questionnaire/search"
    : "http://localhost:8080/questionnaire/list";

  axios.post(url, payload)
    .then(res => {
      if (res.data.code === 200) {
        const data = res.data.data;

        if (Array.isArray(data)) {
          // search 返回数组：手动分页
          this.total = data.length;
          const start = (this.currentPage - 1) * this.pageSize;
          const end = this.currentPage * this.pageSize;
          this.list = data.slice(start, end);
        } else {
          // list 返回分页对象
          this.list = data.records || [];
          this.total = data.total || 0;
        }
      }
    })
    .catch(err => {
      console.error(err);
      this.$message.error('接口调用失败');
    });
},


  handleCurrentChange(page) {
    this.currentPage = page;
    this.fetchList();
  },


    // 删除
    handleDel(row) {
      this.$confirm('确定删除该问卷吗？', '提示', { type: 'warning' })
        .then(() => {
          axios.delete(`http://localhost:8080/questionnaire/${row.questionnaireId}`)
            .then(res => {
              if (res.data.code === 200) {
                this.$message.success('删除成功')
                const index = this.list.findIndex(item => item.questionnaireId === row.questionnaireId)
                if (index > -1) this.list.splice(index, 1)
                this.total = this.list.length
                if (this.tableData.length === 0 && this.currentPage > 1) {
                  this.currentPage--
                  this.fetchList()
                }
              }
            })
            .catch(() => this.$message.error('删除失败'))
        })
        .catch(() => {})
    },

    // 查看详情
    handleDetail(row) {
      axios.get(`http://localhost:8080/questionnaire/${row.questionnaireId}`)
        .then(res => {
          if (res.data.code === 200) {
            const detail = res.data.data
            this.$alert(
              `
              <p>小区：${detail.communityName}</p>
              <p>问卷名称：${detail.questionnaireName}</p>
              <p>描述：${detail.questionnaireDesc}</p>
              <p>开始时间：${detail.questionnaireStartTime}</p>
              <p>结束时间：${detail.questionnaireEndTime}</p>
              <p>问题数量：${detail.questionNum}</p>
              <p>答卷数量：${detail.questionnaireNum}</p>
              <p>状态：${detail.statusName}</p>
              `,
              '问卷详情',
              { dangerouslyUseHTMLString: true, confirmButtonText: '关闭' }
            ).catch(() => {})
          }
        })
        .catch(() => this.$message.error('获取详情失败'))
    },

    // 打开编辑 Dialog
    openEditDialog(row) {
      axios.get(`http://localhost:8080/questionnaire/${row.questionnaireId}`)
        .then(res => {
          if (res.data.code === 200) {
            this.editForm = { ...res.data.data }
            this.editDialogVisible = true
          }
        })
        .catch(() => this.$message.error('获取数据失败'))
    },

    // 保存编辑
    saveEdit() {
      axios.post('http://localhost:8080/questionnaire/update', this.editForm)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success('修改成功')
            const index = this.list.findIndex(item => item.questionnaireId === this.editForm.questionnaireId)
            if (index > -1) this.list[index] = { ...this.editForm }
            this.editDialogVisible = false
          }
        })
        .catch(() => this.$message.error('修改失败'))
    },

    // 新增
    handleAdd() {
      this.$message.info('新增功能请自行实现')
    }
  }
}
</script>

<style scoped>
.survey-wrap {
  padding: 20px;
  background: #fff;
}
.tool-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.pagination {
  margin-top: 15px;
  text-align: right;
}
.table-head {
  background: #f5f7fa !important;
}
</style>
